#!/usr/bin/env python3
import sys
import re
def extract_service(content):
    r = {
        "rpcs":[]
    }
    match = re.search(r"service\s*(\w+)\s*",content)
    r["title"] = match.group(1)
    rest = content[match.span()[1]:len(content)]
    match = re.findall(r"rpc\s*(\w+)\s*\(\s*(?:stream)?\s*(\w+)\)\s*returns\s*\(\s*(?:stream)?\s*(\w+)\s*\)\s*;",rest)
    for obj in match:
        r["rpcs"].append({
            "name":obj[0],
            "param":obj[1],
            "return":obj[2]
        })
        pass
    return r
    pass
with open(sys.argv[1],"r") as file:
    with open(sys.argv[2],"w") as output:
        content = file.read()
        math = re.findall(r"service\s*\w+\s*\{[^\}]+\}",content)
        services = []
        for v in math:
            v = re.sub(r"//.*;","",v)
            services.append(extract_service(v))
        output.write("#pragma once\n#include <proto_client.hpp>\n\n")
        
# BEGIN_SERVICE(FuckService,test)
#     BIND_FUNC(fuck_add);
# END_SERVICE(FuckService)
        for s in services:
            # print(s["title"])
            output.write("BEGIN_SERVICE({0}_service,{0})\n".format(s["title"]))
            for rpc in s["rpcs"]:
                output.write("\tBIND_FUNC({});\n".format(rpc["name"]))
            output.write("END_SERVICE({0}_service)\n\n".format(s["title"]))
    